package myJs.cps

import myJs.Implicits._
import myJs.myPkg.jquery.{$, JQuery}
import org.scalajs.dom.{Event, html}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.React
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.scalajs.js

/**
 * Created by yz on 21/1/2022
 */
@react object PureTextareaCp {

  case class Props(name: String = "", hasBv: Boolean = false, formJq: JQuery = $("#form"),
                   placeHolder: String = "", value: js.UndefOr[String] = js.undefined,
                   onChange: js.UndefOr[String => Unit] = js.undefined,
                   selfClassName: String = "",
                   rows:String="3"
                  )

  val component = FunctionalComponent[Props] { props =>
    val inputRef = React.createRef[html.Input]

    useEffect(() => {
      if (props.hasBv) {
        val y = inputRef.current
        val bv = props.formJq.bv
        val curJq = $(y)
        bv.addField(curJq).revalidateField(curJq)
      }
    }, List()
    )

    val (myV, setMyV) = useState("")

    def valueChange = (e: SyntheticEvent[TagElement#RefType, Event]) => {
      val v = e.target.asInstanceOf[html.Input].value
      props.onChange.toOption match {
        case Some(f) => f(v)
        case None => setMyV(v)
      }
    }

    val v = props.value.map { x => x }.getOrElse(myV)

    textarea(style := Style(width = "100%"), className := s"form-control fillByName ${props.selfClassName}",
      name := s"${props.name}", value := s"${v}",
      placeholder := props.placeHolder, ref := inputRef, onChange := valueChange,
      rows := props.rows
    )


  }

}
